package com.xr.blog.tools;

import com.xr.blog.exception.CustomException;
import com.xr.blog.tools.constant.Code;
import com.xr.blog.tools.spring.SpringUtils;
import com.xr.blog.tools.storage.StorageConfig;
import com.xr.blog.tools.storage.group.AliyunGroup;
import com.xr.blog.tools.storage.group.LocalGroup;
import com.xr.blog.tools.storage.group.QcloudGroup;
import com.xr.blog.tools.storage.group.QiniuGroup;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;
/**
 * hibernate-validator校验工具类
 *
 * @author XRJ
 * @email 1033835209@qq.com
 * @date 2020-08-28 17:09:38
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = SpringUtils.getBean(Validator.class);
    }


    public static void isBlank(String str, String message) {
        if (StringUtils.isBlank(str)) {
            throw new CustomException(message,Code.SC_PRECONDITION_FAILED.getState());
        }
    }

    public static void isNull(Object obj, String message) {
        if (obj==null) {
            throw new CustomException(message,Code.SC_PRECONDITION_FAILED.getState());
        }
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws CustomException  校验不通过，则报BlogException异常
     */
    public static void validate(Object object, Class<?>... groups) throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getMessage());
            }
            throw new CustomException(msg.toString(),Code.SC_PRECONDITION_FAILED.getState());
        }
    }

    /**
     * 校验存储配置信息
     * @param value  待校验的值
     * @throws CustomException  校验不通过，则报BlogException异常
     */
    public static void validateStorageConfig(String value) throws CustomException {
        StorageConfig storageConfig= JsonUtils.fromJson(value,StorageConfig.class);
        if(storageConfig.getType() == Code.QINIU){
            //校验七牛数据
            validate(storageConfig, QiniuGroup.class);
        }else if(storageConfig.getType() == Code.ALIYUN){
            //校验阿里云数据
            validate(storageConfig, AliyunGroup.class);
        }else if(storageConfig.getType() == Code.QCLOUD){
            //校验腾讯云数据
            validate(storageConfig, QcloudGroup.class);
        }else if(storageConfig.getType() == Code.LOCAL){
            //校验本地数据
            validate(storageConfig, LocalGroup.class);
        }
    }
}
